In the second catch{}
block of the inner try{}
block.
import java.io.*; class ReadIntEOF { public static void main ( String[] args ) { String fileName = "ints.dat" ; long sum = 0; try { DataInputStream instr = new DataInputStream( new BufferedInputStream( new FileInputStream( fileName ) ) ); try { while ( true ) sum += instr.readInt(); } catch ( EOFException eof ) { System.out.println( "The sum is: " + sum ); instr.close(); } catch ( IOException iox ) { System.out.println( "Problems reading " + fileName ); instr.close(); } } catch ( IOException iox ) { System.out.println("I/O Problems with " + fileName ); } } }
Here is the complete program to read in integers (and process them) until end of file. If you want to copy this program to a file and run it, you will need a binary file of integers. The "data translator" program from programming exercise one of the previous chapter can be used for that.
If things go wrong, might this program try to close a file that failed to open?